//秒杀数量控制

package main

import (
	"fmt"
	"kill/common"
	"kill/repositories"
	"kill/services"
	"log"
	"net/http"
	"sync"
)

var sum int64 = 0

// 预存商品数量
var productNum int64

// 互斥锁
var mutex sync.Mutex

// 计数
var count int64 = 0

// 获取秒杀商品
func GetOneProduct() bool {
	//加锁
	mutex.Lock()
	defer mutex.Unlock()
	count += 1
	//判断数据是否超限
	if sum < productNum {
		sum += 1
		fmt.Println(sum)
		return true
	}

	return false

}

func GetProduct(w http.ResponseWriter, req *http.Request) {
	if GetOneProduct() {
		w.Write([]byte("true"))
		return
	}
	w.Write([]byte("false"))
	return
}

func main() {
	//产品数量控制
	db, _ := common.NewMysqlConn()
	productManage := repositories.NewProductManager("product", db)
	productNumServices := services.NewProductService(productManage)
	product, err := productNumServices.GetProductByID(1)
	if err != nil {
		log.Fatal("Err:", err)
	}
	productNum = product.ProductNum
	//A产品数量控制

	http.HandleFunc("/getOne", GetProduct)
	err = http.ListenAndServe(":8084", nil)
	if err != nil {
		log.Fatal("Err:", err)
	}
}
